package alipay;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONException;
import org.json.JSONObject;

import share.Const;
import share.HttpIP;

/**
 * 调用支付宝支付startPay（）方法
 */
public class PayTool {

    private static PayTool instance;
    private Context mcontext;
    private PayCallback callback;
//    private WaitDialog mWaitDialog;

    public static PayTool getInstance() {
        if (instance == null) {
            instance = new PayTool();
        }
        return instance;
    }

    public void startPay(Activity context, PayCallback callback, String[] params) {
        this.callback = callback;

        new PayAysncTask(context).execute(params);
    }

    private class PayAysncTask extends AsyncTask<String, Void, String> {

        private Activity context;

        PayAysncTask(Activity context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
//            mWaitDialog = new WaitDialog(context);
//            mWaitDialog.setCancelable(false);
//            mWaitDialog.setMessage("正在提交...");
//            mWaitDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.Buy, Const.POST);
        mRequest.addHeader("token",params[0]);
        mRequest.add("count",params[1]);
        mRequest.add("price",params[2]);
        mRequest.add("targetName",params[3]);//
        mRequest.add("payType","Alipay");
        mRequest.add("targetIntro",params[4]);
        Response<String> response = NoHttp.startRequestSync(mRequest);
        if(response.isSucceed())

        {
            Log.i("onSucceed", "请求成功：\n" + response.get());
            try {
                JSONObject obj = new JSONObject(response.get());
                if (obj == null) {
                    return "支付失败！";
                }
//                    String payInfo = "partner=2088521596712505&seller_id=2088521596712505&out_trade_no=201702073574091&subject=天上人间&body=天上人间&total_fee=0.01&notify_url=http://szsfk.weiruanmeng.com/PayAli/notify_url.php&service=mobile.securitypay.pay&payment_type=1&_input_charset=utf-8&it_b_pay=1d&sign=A9D2KsAvE3U0l82S83ENrydcz2cK9kTrv9vX3Kp5ysOdTWWMeX%2BpuIZbQ2e3%2FRS4VE59cnmIg97zeqOLAvcxgK53i6jD%2FN%2BC9OZllZXsZi6zi54BC1G2tUpYH9kfWU%2F9jvHipHYx1GEJuWm%2Ba1sHOnhzk7PlF17RmLWAk27HR20%3D&sign_type=RSA";
//                    String payInfo = "_input_charset=utf-8&body=永丰心座2号楼1单元5层10号-A房间&it_b_pay=1d&notify_url=http://heheyu.weiruanmeng.com/PayAli/notify_url.php&out_trade_no=2017020730912521&partner=2088521231569824&payment_type=1&seller_id=2088521231569824&service=mobile.securitypay.pay&subject=永丰心座2号楼1单元5层10号-A房间&total_fee=15678.32&sign=m3QcWbsGYG0QOENb3HMuhqEsouK6nQvKqL2YBJkW7BDAxzXd86FFPJQo%2F5T4PEcLkxx73YiykbYp5C1NaaBP7YxhqJICwDnWhPqjeCp4zq1nMsSdes43SPKgdZccibxSwY6No4UBO%2BKbb3%2B8PhJOoA29Er83cCRyLriUseJsj8c%3D&sign_type=RSA";
                String payInfo = obj.getString("data");
                // 构造PayTask 对象
                PayTask alipay = new PayTask(context);
                // 调用支付接口，获取支付结果
                return alipay.pay(payInfo, true);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        return"支付失败！"; // 请求失败
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
//            if (mWaitDialog != null) {
//                mWaitDialog.dismiss();
//            }

        if (!TextUtils.equals("支付失败！", result)) {
            PayResult payResult = new PayResult(result);
            /**
             * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
             * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
             * docType=1) 建议商户依赖异步通知
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            Log.i("PayResult", "onPostExecute: " + resultInfo);

            String resultStatus = payResult.getResultStatus();
            // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
            // 判断resultStatus 为非"9000"则代表可能支付失败
            // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误

            if (TextUtils.equals("9000", resultStatus)) callback.doWork(resultStatus, true);
            else callback.doWork(resultStatus, false);
        } else {
            callback.doWork(result, false);
        }
    }

}

public interface PayCallback {
    public void doWork(String payResult, boolean isDone);
}

}
